package leetCode.sample;

import org.junit.Test;

/**
 * @author: zhangzhiping
 * @date: 2019/6/12 18:30
 * @description: 反转有符号数
 */
public class ReverseSignedNumber {

    public static int reverse(int x) {
        int num = x;
        int resultNum = 0;
        int negative = 1;
        if (x < 0) {
            negative = -1;
            num = x * negative;
        }
        while (num > 0) {
            int i = 9;
            int temp = resultNum;
            while (i > 0) {
                if (resultNum + temp < resultNum) {
                    return 0;
                }
                resultNum = resultNum + temp;
                i--;
            }
            resultNum = resultNum + num % 10;
            num = num / 10;
        }
        resultNum = resultNum * negative;
        return resultNum;
    }

    public int reverse2(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }

    @Test
    public void test() {
        System.out.println(reverse(120));
        System.out.println(reverse(-123));
        System.out.println(reverse(1534236469));

        System.out.println(reverse2(120));
        System.out.println(reverse2(-123));
        System.out.println(reverse2(1534236469));
    }
}
